﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SoccerEvaluator.Common;
using SoccerEvaluator.Business;
using System.Web.UI.HtmlControls;
using SoccerEvaluator.WebSite.App_Code;

namespace SoccerEvaluator.WebSite
{
    public partial class MatchUser : System.Web.UI.Page
    {
        /// <summary>
        ///
        /// </summary>
        protected int _projectID
        {
            get
            {
                if (Request.QueryString["ID"] != null)
                {
                    return int.Parse(Request.QueryString["ID"]);
                }
                else return 0;
            }
        }

        /// <summary>
        ///
        /// </summary>
        protected int _userID
        {
            get
            {
                if (Request.QueryString["userId"] != null)
                {
                    return int.Parse(Request.QueryString["userId"]);
                }
                else return 0;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private string _name;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                SoccerEvaluatorModelContainer context = new SoccerEvaluatorModelContainer();

                SystemUser user = context.SystemUsers.FirstOrDefault(c => c.Id == _userID);

                this._name = user.Name;

                this.lblUserName.Text = string.Format("{0}  ({1})", user.Name, user.UserName);

                this.RenderUserScore();
            }

        }
        /// <summary>
        /// 
        /// </summary>
        private void RenderUserScore()
        {


            SoccerEvaluatorModelContainer context = new SoccerEvaluatorModelContainer();

            TemplateInfo projectInfo = ObjectFactory.ToTemplateInfo(context.Templates.FirstOrDefault(c => c.Id == _projectID));

            //Si el proyecto esta en modo play
            /*
            if (projectInfo.ProjectMode == (int)ProjectMode.Play)
            {
                RenderUserScore(projectInfo);

                this.cmbTeam.DataSource = SoccerEvaluator.Business.Util.GetDistinct(projectInfo.Scores);
                this.cmbTeam.DataBind();
                this.cmbTeam.Items.Insert(0, new ListItem((string)HttpContext.GetGlobalResourceObject("Resource", "All"), "-1"));
                this.cmbTeam.SelectedIndex = 0;
            }
            else
            {
                Response.Redirect("MatchList.aspx?message=CannotViewUser");
            }
            */


            RenderUserScore(projectInfo);

            this.cmbTeam.DataSource = SoccerEvaluator.Business.Util.GetDistinct(projectInfo.Scores);
            this.cmbTeam.DataBind();
            this.cmbTeam.Items.Insert(0, new ListItem((string)HttpContext.GetGlobalResourceObject("Resource", "All"), "-1"));
            this.cmbTeam.SelectedIndex = 0;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="loader"></param>
        /// <param name="projectInfo"></param>
        private void RenderUserScore(TemplateInfo projectInfo)
        {
            SoccerEvaluatorModelContainer context = new SoccerEvaluatorModelContainer();

            SystemUser dbUser = context.SystemUsers.FirstOrDefault(c => c.Id == _userID);

            SystemUserInfo userInfo = ObjectFactory.ToSystemUserInfo(dbUser);

            this.txtRowstoEvaluate.Text = projectInfo.Scores.Count.ToString();

            //Prepara un evaluador de resultados
            Evaluator eval = new Evaluator(projectInfo.ExactScore, "96FF96", projectInfo.CatchScore, "B4B4FF");

            TemplateInfo newUserTemplate = new TemplateInfo();

            newUserTemplate.Name = dbUser.Name;

            newUserTemplate.Scores = ObjectFactory.ToTemplateScoreInfoList(context.UserScores.Where(c => c.SystemUserId == _userID && c.TemplateId == _projectID).ToList());

            //Evalua los resultados frente a la plantilla de la fifa
            newUserTemplate.Total = eval.Evaluate(projectInfo, newUserTemplate);

            //Coloca los resultados de la evaluacion
            this.lblExactScore.Text = string.Format("{0} x {1} = {2}", projectInfo.ExactScore, newUserTemplate.ExactScore, projectInfo.ExactScore * newUserTemplate.ExactScore);
            this.lblCatchScore.Text = string.Format("{0} x {1} = {2}", projectInfo.CatchScore, newUserTemplate.CatchScore, projectInfo.CatchScore * newUserTemplate.CatchScore);
            this.lblTotalScore.Text = newUserTemplate.Total.ToString();
            this.lblUserName.Text = userInfo.Name;

            this.lstScores.DataSource = newUserTemplate.Scores;
            this.lstScores.DataBind();
        }

        /// <summary>
        /// 
        /// </summary>
        private void FilterScoresByDate()
        {
            string userName = Request.QueryString["user"];

            SoccerEvaluatorModelContainer context = new SoccerEvaluatorModelContainer();

            SystemUser dbUser = context.SystemUsers.FirstOrDefault(c => c.UserName == userName);

            TemplateInfo projectInfo = ObjectFactory.ToTemplateInfo(context.Templates.FirstOrDefault(c => c.Id == _projectID));

            TemplateInfo userResults = ObjectFactory.ToTemplateInfo(context.Templates.FirstOrDefault(c => c.Id == projectInfo.ID));

            FilterInfo f = new FilterInfo();

            List<TemplateScoreInfo> list = Util.Filter(f, userResults.Scores);

            string templatePath = Server.MapPath(string.Format(@"~\Projects\{0}\{0}.xml", _projectID));

            List<TemplateScoreInfo> FIFAlist = Util.Filter(f, projectInfo.Scores);

            //Prepara un evaluador de resultados
            Evaluator eval = new Evaluator(projectInfo.ExactScore, "96FF96", projectInfo.CatchScore, "B4B4FF");

            //Evalua los resultados frente a la plantilla de la fifa
            // userResults = eval.Evaluate(projectInfo.Scores.Count, projectInfo, userResults);

            this.lstScores.DataSource = userResults.Scores;
            this.lstScores.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        private void FilterScores()
        {
            /*
            string userName = Request.QueryString["user"];

            Template loader = new Template();

            string tPath = string.Format(@"~\Projects\{0}\{1}.xml", _projectId, userName);

            TemplateInfo result = loader.LoadResult(Server.MapPath(tPath));

            FilterInfo f = new FilterInfo();

            int value = int.Parse(cmbPlayed.SelectedValue);

            if (value != -1)
            {
                f.Enabled = value;
            }

            if (this.cmbTeam.SelectedValue != "-1")
            {
                string teamName = this.cmbTeam.SelectedValue;

                f.Visitor = teamName;
                f.Local = teamName;
            }

            List<ScoreInfo> list = Util.Filter(f, result.Scores);

            this.lstScores.DataSource = list;
            this.lstScores.DataBind();
             */
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cmbTeam_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.FilterScores();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cmbPlayed_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.FilterScores();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            this.RenderUserScore();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lstScores_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem != null)
            {
                TemplateScoreInfo s = (TemplateScoreInfo)e.Item.DataItem;

                HtmlTableRow row = (HtmlTableRow)e.Item.FindControl("row");

                if (s.Color == null)
                {
                    row.Attributes.Add("class", "ScoreLine");
                }
                else
                {
                    TimeSpan ts = DateTime.Now - s.Date;

                    if (ts.TotalMilliseconds > 0)
                    {
                        row.Attributes.Add("class", "UserDeactivated");
                    }
                    else
                    {
                        row.Attributes.Add("class", "UserScoreLine");
                    }

                    row.Attributes.Add("bgColor", s.Color);
                }
            }
        }
    }
}